#include "GlobalDataMgr.h"
#include "db_driver/db_driver.h"
#include "RelaSvr.h"
#include "player/RelaPlayerMgr.h"
#include "player/MailBoxMgr.h"


REG_EVENT(EVENTID::ON_DB_CON, GlobalDataMgr::OnDbCon)
void GlobalDataMgr::OnDbCon()
{
	{
		auto f = [](const DbGlobalData* data)
		{
			if (nullptr == data)
			{
				LDEBUG("load m_DbSvrBase fail, init DbGlobalData");
				GlobalDataMgr::Ins().m_DbSvrBase.startTimestamp = SysTime::Ins().Sec();
			}
			else
			{
				proto::Unpack(GlobalDataMgr::Ins().m_DbSvrBase, data->serial);
				LDEBUG("load m_DbSvrBase ok");
			}
			RelaSvr::Ins().SetReady(ReadyType::LOAD_SVR_BASE);
			RelaSvr::Ins().CallAllZone("UpdateDbSvrBase", GlobalDataMgr::Ins().m_DbSvrBase);
		};
		string cond = "id = " + StrNum::NumToStr((int)GlobalType::SVR_BASE);
		Dbproxy::Ins().QueryCond(cond, f);
	}

	{
		auto f = [](const DbGlobalData* data)
		{
			if (nullptr == data)
			{
				LDEBUG("load RANK_DEMO fail, init RANK_DEMO");
			}
			else
			{
				proto::Unpack(GlobalDataMgr::Ins().m_DbBroadCastMail, data->serial);
				LDEBUG("load RANK_DEMO ok");
			}
			gRelaSvr.SetReady(ReadyType::LOAD_BROAD_CAST_MAIL);
		};
		string cond = "id = " + StrNum::NumToStr((int)GlobalType::BROADCAST_MAIL);
		Dbproxy::Ins().QueryCond(cond, f);
	}
}
static int32 MAX_MSG_DATA_LEN = 100;

void GlobalDataMgr::SaveDbSvrBase()
{
	DbGlobalData d;
	d.id = (uint64)GlobalType::SVR_BASE;
	L_COND_V(proto::Pack(m_DbSvrBase, d.serial));
	Dbproxy::Ins().Update(d);
}

void GlobalDataMgr::SaveDbRankDemo()
{
	DbGlobalData d;
	d.id = (uint64)GlobalType::BROADCAST_MAIL;
	L_COND_V(proto::Pack(m_DbBroadCastMail, d.serial));
	Dbproxy::Ins().Update(d);
}

void GlobalDataMgr::SetDbSvrBaseDirty()
{
	if (m_DbSvrBaseDirtyTimer.IsTiming())
	{
		return;
	}
	auto f = [this]()
	{
		SaveDbSvrBase();
	};
	m_DbSvrBaseDirtyTimer.Start(60 * 5, f);
}

void GlobalDataMgr::SetDbBroadcastMailDirty()
{
	if (m_DbRankDemoDirtyTimer.IsTiming())
	{
		return;
	}
	auto f = [this]()
	{
		SaveDbRankDemo();
	};
	m_DbRankDemoDirtyTimer.Start(60 * 5, f);
}

void GlobalDataMgr::AddBroadcastMail(const std::string& title, const std::string& content)
{
	uint64 id = ++m_DbBroadCastMail.sysMailIdSeed;
	auto& id2SysMail = m_DbBroadCastMail.id2SysMail;
	L_COND_V(id2SysMail.find(id) == id2SysMail.end());
	DbMail& mail = id2SysMail[id];
	mail.id = id;
	mail.title = title;
	mail.content = content;
	mail.timestamp = gSysTime.Sec();

	for (auto& i : gMailBoxMgr.m_id2data)
	{
		MailBox& d = i.second;
		d.AddBroadCastMail(mail);
	}
	if (id2SysMail.size() > MAX_SYS_MAIL_NUM)
	{
		id2SysMail.erase(id2SysMail.begin());
	}
	SetDbBroadcastMailDirty();
}
